#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#       File: afla_func.py
#       Author: Finnur Smári Torfason
# 	    Date: 05/01/2012
# 	    Föll og klasar fyrir aflalista
#

import urllib2, socket, re, sqlite3,  helpers

socket.setdefaulttimeout(10) # Til að forritið hangi ekki

#########################################################
#												Föll														#
#########################################################

def gatherInfo(id, kvtime, error=0):
  urlBase = 'http://www.fiskistofa.is/veidar/aflastada/einstokskip?fyrirsp=00&skipnr='

  site = None
  name = None
  size = None
  cat = None
  landing = 0

  try:
    site = urllib2.urlopen(urlBase + str(id) + '&kvtime=' + str(kvtime)) # Sæki vefsíðu
    site = unicode(site.read(), site.headers['content-type'].split('charset=')[-1]) # Fyrir íslenska stafi

  except (urllib2.URLError, socket.timeout):
    error = 1
  except (LookupError):
    print "LookupError: \n"
    print site
    error = 1

  if error == 0: # Náum í upplýsingarnar ef engin villa

    try:
      # Nafn skips
      tmpSite = site.encode('utf-8')

      if 'Útgerðarflokkur' in tmpSite: # Náum í útgerðarflokk
        cat = tmpSite.split('Útgerðarflokkur')
        cat = cat[1].split('</p></td><td>')
        cat = cat[1].split('</td></tr>')
        cat = cat[0]
        cat = cat.replace("'", "")

        if 'Nafn' in tmpSite:
          name = tmpSite.split('<h2 class="boxhead">') # Náum i nafnið
          name = name[1].split(' (')
          name = name[0]
          name = name.replace("'", "")

        if 'Brúttótonn' in tmpSite: # Náum í stærð
          size = tmpSite.split('Brúttótonn')
          size = size[1].split('</p></td><td>')
          size = size[1].split('</td></tr>')
          size = size[0]
          size = size.replace("'", "")

        if 'Landanir' in tmpSite: # Athugum hvort báturinn eigi löndun á kvótaárinu
          landing = 1
    except IndexError:
      error = 1

  info = (id, name, size, cat, landing, kvtime)

  return (info, error)

#
# Fallið sækir upplýsingar um númer, dagsetningu og höfn löndunar, og veiðarfæri í túrnum
#
def gatherLanding(id, kvtime, error=0):
  urlBase = 'http://www.fiskistofa.is/veidar/aflastada/einstokskip?fyrirsp=80&skipnr='

  lURL = None
  lDate = None
  fGear = None
  harbour = None

  try:
    site = urllib2.urlopen(urlBase + str(id) + '&kvtime=' + str(kvtime))
    site = unicode(site.read(), site.headers['content-type'].split('charset=')[-1]) # Fyrir íslenska stafi
  except (urllib2.URLError, socket.timeout):
    error = 1
  except (LookupError):
    print "LookupError: \n"
    print site
    error = 1

  if error == 0:
    try:
      landing = site.split('<tr><td class')
      landing[len(landing)-1] = landing[len(landing)-1].split('</table>')[0]

      lURL = []
      lDate = []
      fGear = []
      harbour = []

      lDate = helpers.dateFormat(re.findall(r'\d\d.\d\d.\d\d\d\d', site.split('text-align:right')[1]))
      for i in range(1,len(landing)):
        if 'staffgraenn' in landing[i]:
          landing[i] = landing[i].replace('staffgraenn', '')

        tmp = landing[i].split('<a href=\'')
        lURL.append(tmp[1].split('\' > ')[0])

        tmp = landing[i].split('<td class=\' \' >')
        fGear.append(tmp[1].split('</td>')[0])
        harbour.append(tmp[2].split('</td>')[0])
    except IndexError:
      error = 1

  landingInfo = (id, lURL, lDate, fGear, harbour)

  return (landingInfo, error)

#
# Fallið sækir upplýsingar um heildarafla löndunar og afla einstakra fisktegunda
#
def landingInfo(urlExt, error=0):
  urlBase = 'http://www.fiskistofa.is/veidar/aflastada/einstokskip'

  fType = None
  fTotal = None
  total = None

  try:
    site = urllib2.urlopen(urlBase + urlExt)
    site = unicode(site.read(), site.headers['content-type'].split('charset=')[-1]) # Fyrir íslenska stafi
  except (urllib2.URLError, socket.timeout):
    error = 1
  except (LookupError):
    print "LookupError: \n"
    print site
    error = 1

  if error == 0:

    try:
      tmpType = []
      tmpTotal = []
      fType = ""
      fTotal = ""

      landing = site.split('</table><table width=\'100%\'>')[1]
      landing = landing.split('</td><td colspan=\'5\'>')[0].replace('staffgraenn','')
      landing = landing.split('</td></tr><tr>')

      for i in range(2,len(landing)-1):
        tmp1 = landing[i].split('<td class=\' \' >')[1]
        tmp2 = landing[i].split('<td class=\' tolur \' >')[1]

        tmpType.append(tmp1.split('</td>')[0])
        tmpTotal.append(tmp2.split('</td>')[0].replace('.', ''))

      total = landing[len(landing)-1].split('<strong>')[2]
      total = total.split('</strong>')[0].replace('.', '')

      for i in range(0,len(tmpType)):
        if i == 0:
          fType = tmpType[i]
          fTotal = tmpTotal[i]
        else:
          fType = fType + ', ' + tmpType[i]
          fTotal = fTotal + ', ' + tmpTotal[i]
      fType = fType.replace("'", "")
    except IndexError:
      error = 1

  landings = (total, fType, fTotal)

  return (landings, error)

##################################################################
if __name__ == '__main__':
  for i in range(80,90):
    gatherInfo(i, 1011)

#  for i in range(80,90):
#    gatherLanding(i,1112)
#
#  landingInfo('?fyrirsp=80&skipnr=89&kvtime=1112&komunr=-251619')
  landingInfo('?fyrirsp=80&skipnr=2433&kvtime=1112&komunr=151423')
##################################################################

